<template>
  <div class="admin-dashboard">
    <!-- 数据筛选 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange.start"
            type="date"
            placeholder="开始日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          ></el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange.end"
            type="date"
            placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          ></el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="fetchData"
          >
            刷新数据
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 数字统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <i class="el-icon-document stat-icon"></i>
            <div class="stat-info">
              <div class="stat-label">询标数量</div>
              <div class="stat-value">{{ statistics.InquiryNum }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <i class="el-icon-chat-line-round stat-icon"></i>
            <div class="stat-info">
              <div class="stat-label">回复数量</div>
              <div class="stat-value">{{ statistics.ReplyNum }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <i class="el-icon-message stat-icon"></i>
            <div class="stat-info">
              <div class="stat-label">短信发送</div>
              <div class="stat-value">{{ statistics.SendSMSNum }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <i class="el-icon-phone stat-icon"></i>
            <div class="stat-info">
              <div class="stat-label">语音通知</div>
              <div class="stat-value">{{ statistics.VoiceNotificationNum }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 图表展示 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>询标趋势</span>
          </div>
          <div ref="trendChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>回复率分析</span>
          </div>
          <div ref="replyRateChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { GetAdminHomeData } from '@/api/Dashboard.js'

export default {
  name: 'AdminDashboard',
  data() {
    const getToday = () => {
      const d = new Date()
      return d.toISOString().substr(0, 10)
    }
    const get7DaysAgo = () => {
      const d = new Date()
      d.setDate(d.getDate() - 7)
      return d.toISOString().substr(0, 10)
    }
    return {
      dateRange: {
        start: get7DaysAgo(),
        end: getToday()
      },
      statistics: {
        InquiryNum: 0,
        ReplyNum: 0,
        SendSMSNum: 0,
        VoiceNotificationNum: 0,
        ReplyRate: 0
      },
      trendChart: null,
      replyRateChart: null
    }
  },
  methods: {
    initCharts() {
      // 询标趋势图
      this.trendChart = echarts.init(this.$refs.trendChartRef)
      this.trendChart.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{
          name: '询标数',
          data: [],
          type: 'line',
          smooth: true
        }]
      })

      // 回复率分析图
      this.replyRateChart = echarts.init(this.$refs.replyRateChartRef)
      this.replyRateChart.setOption({
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          type: 'pie',
          radius: '50%',
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0,0,0,0.5)'
            }
          }
        }]
      })
    },

    async fetchData() {
      try {
        const res = await GetAdminHomeData({
          start: this.dateRange.start,
          end: this.dateRange.end
        })
        if (res && res.Data) {
          // 统计数据（避免空值合并/可选链，提高兼容性）
          this.statistics.InquiryNum = res.Data.InquiryNum != null ? res.Data.InquiryNum : 0
          this.statistics.ReplyNum = res.Data.ReplyNum != null ? res.Data.ReplyNum : 0
          this.statistics.SendSMSNum = res.Data.SendSMSNum != null ? res.Data.SendSMSNum : 0
          this.statistics.VoiceNotificationNum = res.Data.VoiceNotificationNum != null ? res.Data.VoiceNotificationNum : 0
          this.statistics.ReplyRate = res.Data.ReplyRate != null ? res.Data.ReplyRate : 0

          const trends = res.Data.InquiryTrends || []
          const xAxisData = trends.map(item => item.Day)
          const seriesData = trends.map(item => item.InquiryNum)

          if (this.trendChart) {
            this.trendChart.setOption({
              xAxis: { data: xAxisData },
              series: [{ data: seriesData }]
            })
          }

          if (this.replyRateChart) {
            const unReply = Math.max(this.statistics.InquiryNum - this.statistics.ReplyNum, 0)
            this.replyRateChart.setOption({
              series: [{
                data: [
                  { value: this.statistics.ReplyNum, name: '已回复' },
                  { value: unReply, name: '未回复' }
                ]
              }]
            })
          }
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },

    handleResize() {
      if (this.trendChart) this.trendChart.resize()
      if (this.replyRateChart) this.replyRateChart.resize()
    }
  },

  mounted() {
    this.initCharts()
    this.fetchData()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.trendChart) { this.trendChart.dispose(); this.trendChart = null }
    if (this.replyRateChart) { this.replyRateChart.dispose(); this.replyRateChart = null }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 24px;
}

.filter-card {
  margin-bottom: 24px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 16px;
}

.stat-icon {
  font-size: 32px;
  color: #409EFF;
  margin-right: 16px;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.charts-row {
  margin-bottom: 24px;
}

.chart-card {
  min-height: 400px;
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-dashboard {
    padding: 16px;
  }
  
  .stat-card {
    margin-bottom: 16px;
  }
  
  .chart-card {
    margin-bottom: 16px;
  }
}
</style>